<?php

/**
 * descript:
 * User: blue
 * Date: 2018/9/11 16:45
 */

namespace app\api\model;

use app\library\base\BaseModel;
use app\library\except\DataException;
use think\Db;

class User extends BaseModel
{
    protected $insertFields=['name','password'];
    protected $autoWriteTimestamp=true;

    public function GroupM2M(){
        return $this->belongsToMany('Group','auth_group_access','group_id','uid');
    }

    //修改器
    public function setPasswordAttr($value){
        return password_hash($value,PASSWORD_DEFAULT);
    }

    public function regist($data){
        $res=$this->allowField(['name','password'])->save($data);
        if(!$res){
            throw new DataException();
        }
    }

    /**更新密码
     * @param $data 前台传递的数据
     * @return bool
     */
    public function updatePassword($data){
        // $data['password']=password_hash($data['password'],PASSWORD_DEFAULT);
        $email=$data['email'];
        $uobj=self::where('name',$email)->find();
        $uobj->password=$data['password'];
        $res=$uobj->save();
        if(!$res){
            throw new Exception('数据写入失败');
        }
        return true;
    }

    //删除用户表时删除中间表
    protected function after_delete($ids)
    {
        //where in $ids为单个字符串时是否正确
        $res=Db::table('think_auth_group_access')->whereIn('uid',$ids)->delete();
    }
}